<template>
  <view class="travel-detail">
    <!-- 价格日历弹窗 -->
    <u-popup v-model="showCalendarPopup" mode="bottom" border-radius="24" closeable>
      <view class="calendar-popup">
        <!-- 弹窗头部 -->
        <view class="calendar-header">
          <text class="calendar-title">{{ textMap.calendarTitle }}</text>
          <view class="calendar-nav">
            <text class="nav-btn" @click="prevYear">{{ textMap.prevYear }}</text>
            <text class="nav-btn" @click="prevMonth">{{ textMap.prevMonth }}</text>
            <text class="current-month">{{ currentYear }}年{{ currentMonth }}月</text>
            <text class="nav-btn" @click="nextMonth">{{ textMap.nextMonth }}</text>
            <text class="nav-btn" @click="nextYear">{{ textMap.nextYear }}</text>
          </view>
        </view>

        <!-- 星期标题 -->
        <view class="week-header">
          <view class="week-item" v-for="(day, index) in weekDays" :key="index" :class="{ 'weekend': index >= 5 }">
            {{ day }}
          </view>
        </view>

        <!-- 日期网格 -->
        <view class="date-grid">
          <view class="date-item" v-for="(date, index) in calendarDates" :key="index" :class="{
            'prev-month': date.isPrevMonth,
            'next-month': date.isNextMonth,
            'current-month': date.isCurrentMonth,
            'selected': date.isSelected,
            'today': date.isToday,
            'disabled': date.isDisabled,
            'available': date.isAvailable
          }" @click="selectCalendarDate(date)">
            <text class="date-number">{{ date.day }}</text>
            <view class="date-price" v-if="date.isAvailable && date.price">
              <text class="price-text">{{ textMap.priceSymbol }}{{ date.price }}</text>
            </view>
            <view class="date-status" v-if="date.isAvailable">
              <text class="status-text" :class="date.stockStatus">{{ date.stockText }}</text>
            </view>
          </view>
        </view>

        <!-- 底部确认按钮 -->
        <view class="calendar-footer">
          <view class="selected-info" v-if="selectedCalendarDate">
            <text class="selected-date">{{ selectedCalendarDateText }}</text>
            <text class="selected-price" v-if="selectedCalendarDate.price">{{ textMap.priceSymbol }}{{
              selectedCalendarDate.price }}</text>
            <text class="selected-price" v-else>暂无价格</text>
          </view>
          <view class="confirm-btn">
            <ZButton type="primary" @click="confirmDateSelection">{{ textMap.confirm }}</ZButton>
          </view>
        </view>
      </view>
    </u-popup>
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{ textMap.loading }}</text>
    </view>

    <!-- 内容区域 -->
    <view v-else>
      <!-- 轮播图 -->
      <view class="travel-swiper">
        <swiper class="swiper" indicator-dots="true" autoplay="false" circular="true">
          <swiper-item v-for="(image, index) in travelImages" :key="index">
            <image :src="image" class="swiper-image" mode="aspectFit"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 产品基本信息 -->
      <view class="travel-info">
        <text class="travel-name">{{ travel.name }}</text>
        <!-- <text class="travel-description">{{ travel.description }}</text> -->
        <view class="travel-meta">
          <text class="sales-info">{{ textMap.sales }}: {{ travel.sales || 0 }}</text>
        </view>
      </view>

      <!-- SKU选择 -->
      <view class="sku-section" v-if="skuList.length > 1">
        <view class="section-title" v-if="false">
          <text class="title-text">{{ skuList.length }}{{ textMap.skuSelect }}</text>
        </view>
        <scroll-view v-if="false" class="sku-scroll" scroll-x="true" :scroll-left="skuScrollLeft" scroll-with-animation="true">
          <view class="sku-list">
            <view class="sku-item" v-for="(sku, index) in skuList" :key="sku.id"
              :class="{ active: selectedSkuIndex === index }" @click="selectSku(index)">
              <view class="sku-header">
                {{ getSkuName(sku) }}
              </view>
              <view class="sku-price-section">
                <text class="sku-price">{{ textMap.priceSymbol }}{{ sku.price }}</text>
                <text class="sku-unit">{{ textMap.startText }}</text>
              </view>
              <!-- <text class="sku-desc">{{ sku.description }}</text> -->
              <view class="check-icon" v-if="selectedSkuIndex === index">
                <text class="check-text">{{ textMap.checkMark }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
        <!-- 规格选择 -->
        <view class="spec-selector" v-if="Object.keys(specOptions).length > 0">
          <view class="spec-section" v-for="specKey in Object.keys(specOptions)" :key="specKey">
            <text class="spec-name">{{ specKey }}</text>
            <scroll-view class="sku-scroll" scroll-x="true" scroll-with-animation="true">
              <view class="sku-list">
                <view
                  class="sku-item"
                  v-for="option in specOptions[specKey]"
                  :key="option"
                  :class="{ active: selectedSpecs[specKey] === option }"
                  @click="selectSpec(specKey, option)"
                >
                  <view class="sku-header">
                    {{ option }}
                  </view>
                  <view class="check-icon" v-if="selectedSpecs[specKey] === option">
                    <text class="check-text">{{ textMap.checkMark }}</text>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>

      <!-- 拼团信息展示 -->
      <view class="group-info-section" v-if="isGroupTravel">
        <view class="section-title">
          <text class="title-text">{{ textMap.groupInfo }}</text>
          <view class="group-status" :class="getGroupStatusClass">
            {{ getGroupStatusText }}
          </view>
        </view>
        
        <view class="group-progress">
          <view class="progress-header">
            <view class="progress-info">
              <text class="current-count">{{ currentGroupCount }}</text>
              <text class="separator">/</text>
              <text class="target-count">{{ targetGroupCount }}</text>
              <text class="unit">人</text>
            </view>
            <view class="progress-percentage">
              {{ groupProgressPercentage }}%
            </view>
          </view>
          
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: groupProgressPercentage + '%' }"></view>
          </view>
          
          <view class="group-details" v-if="false">
            <view class="detail-item">
              <text class="detail-label">开团标准：</text>
              <text class="detail-value">{{ targetGroupCount }}人成团</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">当前进度：</text>
              <text class="detail-value">{{ currentGroupCount }}人已报名</text>
            </view>
            <view class="detail-item" v-if="remainingDays > 0">
              <text class="detail-label">剩余时间：</text>
              <text class="detail-value">{{ remainingDays }}天后开团</text>
            </view>
            <view class="detail-item" v-else>
              <text class="detail-label">开团状态：</text>
              <text class="detail-value success">{{ textMap.groupUpcoming }}</text>
            </view>
          </view>
        </view>
        
        <view class="group-notice">
          <text class="notice-text">拼团成功后，商家将安排出行；如未达到开团人数，将全额退款</text>
        </view>
      </view>

      <!-- 日期选择 -->
      <view class="date-section" v-if="selectedSkuIndex !== -1">
        <view class="section-title">
          <text class="title-text">{{ textMap.date }}</text>
          <text class="calendar-btn" @click="showCalendar">{{ textMap.calendarSelect }}</text>
        </view>
        <scroll-view class="date-scroll" scroll-x="true" :scroll-left="dateScrollLeft" scroll-with-animation="true">
          <view class="date-list">
            <view class="date-item" v-for="(date, index) in dateList" :key="date.id"
              :class="{ active: selectedDateIndex === index, disabled: date.stockStatus === 'sold' || date.status === 0 }"
              @click="selectDate(index)">
              <text class="date-week">{{ date.week }}</text>
              <text class="date-day">{{ date.month }}{{ textMap.dateSeparator }}{{ date.day }}</text>
              <view class="date-price-section">
                <text class="date-price">{{ textMap.priceSymbol }}{{ date.adultPrice }}</text>
                <text class="date-unit"></text>
              </view>
              <text class="date-stock" :class="date.stockStatus">{{ date.stockText }}</text>
              <view class="check-icon" v-if="selectedDateIndex === index">
                <text class="check-text">{{ textMap.checkMark }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <u-sticky>
        <u-tabs :list="tabsList" :is-scroll="true" :current="current" active-color="#FF8D1A" @change="changeTab"></u-tabs>
      </u-sticky>
      <!-- 行程亮点 -->
      <view class="detail-section" id="highlights">
        <view class="section-title">
          <text class="title-text">{{ textMap.highlights }}</text>
          <text class="calendar-btn" @click="copyHighlights" v-if="travel.highlights">复制</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.highlights"></rich-text>
        </view>
      </view>

      <!-- 产品详情 -->
      <view class="detail-section" id="details">
        <view class="section-title">
          <text class="title-text">{{ textMap.travelDetail }}</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.description"></rich-text>
        </view>
      </view>

      <!-- 费用包含 -->
      <view class="detail-section" id="costIncluded">
        <view class="section-title">
          <text class="title-text">{{ textMap.costIncluded }}</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.cost_included"></rich-text>
        </view>
      </view>

      <!-- 费用不含 -->
      <view class="detail-section" id="costExcluded">
        <view class="section-title">
          <text class="title-text">{{ textMap.costExcluded }}</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.cost_excluded"></rich-text>
        </view>
      </view>

      <!-- 退款规则 -->
      <view class="detail-section" id="refundRules">
        <view class="section-title">
          <text class="title-text">{{ textMap.refundRules }}</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.refund_rules"></rich-text>
        </view>
      </view>

      <!-- 预定须知 -->
      <view class="detail-section" id="bookingNotice">
        <view class="section-title">
          <text class="title-text">{{ textMap.bookingNotice }}</text>
        </view>
        <view class="detail-content">
          <rich-text :nodes="travel.booking_notice"></rich-text>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <!-- 客服入口 -->
        <view class="customer-service">
          <button class="service-btn" open-type="contact">
          </button>
          <image src="/static/image/kefu.png" class="service-icon"></image>
          <text class="service-text">联系客服</text>
        </view>
        <view v-if="userInfo.user_type === 3" class="customer-service" @click="openShare">
          <button class="service-btn">
          </button>
          <view class="service-icon">
            <image src="/static/image/share.png" style="width: 54rpx;height: 54rpx;"></image>
          </view>
          <text class="service-text">分享</text>
        </view>

        <!-- 分销用户显示邀请好友按钮 -->
        <view v-if="isDistributor" class="distributor-actions">
          <view class="invite-btn">
            <ZButton type="secondary" @click="goToNext">{{ isGroupTravel ? '去拼团' : '立即购买' }}</ZButton>
          </view>
          <view class="invite-btn">
            <ZButton type="primary" @click="inviteFriend">{{ textMap.inviteFriend }}</ZButton>
          </view>
        </view>
        <!-- 普通用户只显示下一步按钮 -->
        <view v-else class="action-section">
          <ZButton style="width: 100%;" type="primary" @click="goToNext">{{ isGroupTravel ? '去拼团' : '立即购买' }}</ZButton>
        </view>
      </view>
    </view>


    <!-- 海报弹窗（组件） -->
    <SharePoster ref="sharePosterRef" :visible="showPosterModal" @close="closePosterModal" :posterTitle="'分享海报'"
      :cover="travel.cover" :title="travel.name"
      :skuName="getSkuName(skuList[selectedSkuIndex])" :dateText="dateList[selectedDateIndex] && dateList[selectedDateIndex].fullDate" :qrcode="qrcode"
      :distributorName="userInfo.nickname || userInfo.username" :shareUrl="shareUrl" @uploaded="onPosterUploaded" />
  </view>
</template>

<script>
import ZButton from "../../components/ZButton.vue";
import SharePoster from "../../components/SharePoster.vue";

export default {

	// 分享给朋友
	onShareAppMessage() {
		return {

		}
	},
  components: { ZButton, SharePoster },
  data() {
    return {
      tabsList: [
        {
          name: '行程亮点',
          value: 0
        },
        {
          name: '产品详情',
          value: 1
        },

        {
          name: '费用包含',
          value: 2
        },
        {
          name: '费用不含',
          value: 3
        },
        {
          name: '退款规则',
          value: 4
        },
        {
          name: '预定须知',
          value: 5
        }
      ],
      current: 0,
      travelId: null,
      specList: [],
      travel: {},
      travelImages: [],
      skuList: [],
      selectedSkuIndex: 0, // 默认选中第一个SKU
      dateList: [],
      selectedDateIndex: 0, // 默认选中第一个日期
      loading: false,
      skuScrollLeft: 0,
      dateScrollLeft: 0,
      showCalendarPopup: false,
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      selectedCalendarDate: null,
      dateMap: new Map(), // 存储日期和价格信息的映射
      // 文本变量
      textMap: {
        calendarTitle: '选择日期',
        prevYear: '<<',
        prevMonth: '<',
        nextMonth: '>',
        nextYear: '>>',
        confirm: '确定',
        calendarSelect: '日历选择',
        date: '日期',
        nextStep: '立即购买',
        nextStepGroup: '立即拼团',
        inviteFriend: '代订',
        bookNow: '立即购买',
        loading: '加载中...',
        sales: '已售',
        skuSelect: '个选择',
        travelDetail: '产品详情',
        selectDate: '请选择日期',
        dateSelectSuccess: '日期选择成功',
        dateNotAvailable: '该日期不可预订',
        selectPackage: '请选择套餐',
        selectDateRequired: '请选择日期',
        checkMark: '✓',
        yearMonth: '年月',
        priceSymbol: '¥',
        startText: '起',
        dateSeparator: '/',
        highlights: '行程亮点',
        details: '产品详情',
        costIncluded: '费用包含',
        costExcluded: '费用不含',
        refundRules: '退款规则',
        bookingNotice: '预定须知',
        groupInfo: '拼团信息',
        groupSuccess: '拼团成功',
        groupPending: '拼团中',
        groupUpcoming: '即将开团'
      },
      showPosterModal: false,
      qrcode: '',
      shareUrl: '',
      imageUrl: '',
      stickyHeight: 0, // 用于存储sticky元素的高度
      scrollIntoView: '', // 用于scroll-into-view锚点定位
      currentGroupCount: 0, // 当前拼团已报名人数
      selectedSpecs: {} // 存储选中的规格
    }
  },
  watch: {
    selectedDate: {
      handler(newVal) {
        if (newVal) {
          let selectedStock = this.dateList[this.selectedDateIndex];
          let selectedSku = this.skuList[this.selectedSkuIndex];
          this.$api.getTravelOrderList({
            travel_sku_id: selectedSku.id,
            travel_sku_stock_id: selectedStock.id,
          }).then(res => {
            let result = res.filter(item => item.status !== 'canceled' && item.refund_status === -1)
            console.log('result',result)
            this.currentGroupCount = result.reduce((acc, item) => acc + item.count, 0);
          });
        }
      },
      immediate: true
    }
  },
  computed: {

    // 规格选项
    specOptions() {
      const options = {};
      // console.log('this.specList',this.specList)
      // // 从规格列表中生成选项
      // this.specList.forEach(spec => {
      //   console.log('spec',spec)
      //   if (spec.spec_values) {
      //     try {
      //       const specValues = JSON.parse(spec.spec_values);
      //       options[spec.spec_name] = specValues;
      //     } catch (e) {
      //       console.error('解析规格值失败:', e);
      //     }
      //   }
      // });

      // 如果没有规格列表，从SKU中提取
      if (Object.keys(options).length === 0) {
        console.log(this.skuList,'this.skuList')
        this.skuList.forEach(sku => {
          if (sku.spec_combination) {
            try {
              const specs = JSON.parse(sku.spec_combination);
              console.log('specs',specs)
              Object.keys(specs).forEach(key => {
                if (!options[key]) {
                  options[key] = [];
                }
                if (!options[key].includes(specs[key])) {
                  options[key].push(specs[key]);
                }
              });
            } catch (e) {
              console.error('解析规格失败:', e);
            }
          }
        });
      }
      console.log('options',options)
      return options;
    },
    selectedDate() {
      let selectedStock = this.dateList[this.selectedDateIndex];
      let selectedSku = this.skuList[this.selectedSkuIndex];
      return selectedStock && selectedSku ? true : false;
    },
    // 判断是否为分销用户
    isDistributor() {
      return this.userInfo && this.userInfo.user_type === 3;
    },
    // 判断是否为拼团产品
    isGroupTravel() {
      if (this.selectedDateIndex !== -1 && this.dateList.length > 0) {
        const selectedDate = this.dateList[this.selectedDateIndex];
        return selectedDate.is_group === 1;
      }
      return false;
    },
    // 获取拼团目标人数
    targetGroupCount() {
      if (this.selectedDateIndex !== -1 && this.dateList.length > 0) {
        const selectedDate = this.dateList[this.selectedDateIndex];
        console.log('selectedDate',selectedDate)
        return selectedDate.group_adult_people || 0;
      }
      return 0;
    },
    // 计算拼团进度百分比
    groupProgressPercentage() {
      if (this.targetGroupCount === 0) {
        return 0;
      }
      return (this.currentGroupCount / this.targetGroupCount) * 100;
    },
    // 计算剩余天数
    remainingDays() {
      if (!this.travel.group_start_time) {
        return 0;
      }
      const startDate = new Date(this.travel.group_start_time);
      const today = new Date();
      const diffTime = Math.abs(startDate - today);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays;
    },
    // 获取拼团状态文本
    getGroupStatusText() {
      if (this.isGroupTravel) {
        if (this.currentGroupCount >= this.targetGroupCount) {
          return this.textMap.groupSuccess;
        } else if (this.remainingDays > 0) {
          return `${this.remainingDays}天后开团`;
        } else {
          return this.textMap.groupUpcoming;
        }
      }
      return '';
    },
    // 获取拼团状态类
    getGroupStatusClass() {
      if (this.isGroupTravel) {
        if (this.currentGroupCount >= this.targetGroupCount) {
          return 'success';
        } else if (this.remainingDays > 0) {
          return 'pending';
        } else {
          return 'upcoming';
        }
      }
      return '';
    },
    calendarDates() {
      const dates = []
      const year = this.currentYear
      const month = this.currentMonth

      // 当前月第一天
      const firstDay = new Date(year, month - 1, 1)
      // 获取第一天是星期几（0=周日，1=周一...6=周六）
      const firstDayOfWeek = firstDay.getDay()
      
      // 计算需要填充的上个月日期数量
      // 星期标题：日、一、二、三、四、五、六
      // 如果第一天是周日(0)，需要填充0天；如果是周一(1)，需要填充1天；如果是周二(2)，需要填充2天，以此类推
      const prevMonthDays = firstDayOfWeek

      // 添加上个月的日期（填充第一周）
      for (let i = prevMonthDays - 1; i >= 0; i--) {
        const date = new Date(year, month - 1, -i)
        const dateKey = this.formatDateKey(date)
        const dateInfo = this.dateMap.get(dateKey)

        dates.push({
          day: date.getDate(),
          date: date,
          dateKey: dateKey,
          isPrevMonth: true,
          isCurrentMonth: false,
          isNextMonth: false,
          isSelected: this.isDateSelected(date),
          isToday: this.isToday(date),
          isAvailable: !!dateInfo,
          isDisabled: !dateInfo,
          price: dateInfo ? dateInfo.adultPrice : null,
          stockStatus: dateInfo ? dateInfo.stockStatus : null,
          stockText: dateInfo ? dateInfo.stockText : null
        })
      }

      // 添加当前月的日期
      const daysInMonth = new Date(year, month, 0).getDate();
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month - 1, day)
        const dateKey = this.formatDateKey(date)
        const dateInfo = this.dateMap.get(dateKey)

        dates.push({
          day: day,
          date: date,
          dateKey: dateKey,
          isPrevMonth: false,
          isCurrentMonth: true,
          isNextMonth: false,
          isSelected: this.isDateSelected(date),
          isToday: this.isToday(date),
          isAvailable: !!dateInfo,
          isDisabled: !dateInfo,
          price: dateInfo ? dateInfo.adultPrice : null,
          stockStatus: dateInfo ? dateInfo.stockStatus : null,
          stockText: dateInfo ? dateInfo.stockText : null
        })
      }

      // 添加下个月的日期（填充最后一周）
      const totalCells = 42 // 6行 × 7列
      const remainingCells = totalCells - dates.length
      for (let day = 1; day <= remainingCells; day++) {
        const date = new Date(year, month, day)
        const dateKey = this.formatDateKey(date)
        const dateInfo = this.dateMap.get(dateKey)

        dates.push({
          day: day,
          date: date,
          dateKey: dateKey,
          isPrevMonth: false,
          isCurrentMonth: false,
          isNextMonth: true,
          isSelected: this.isDateSelected(date),
          isToday: this.isToday(date),
          isAvailable: !!dateInfo,
          isDisabled: !dateInfo,
          price: dateInfo ? dateInfo.adultPrice : null,
          stockStatus: dateInfo ? dateInfo.stockStatus : null,
          stockText: dateInfo ? dateInfo.stockText : null
        })
      }

      return dates
    },
    selectedCalendarDateText() {
      if (!this.selectedCalendarDate) return ''
      const date = this.selectedCalendarDate.date
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
  },
  onLoad(options) {
    console.log('旅行商品详情页面加载，参数:', options);

    if (options.id) {
      this.travelId = parseInt(options.id);
      this.loadTravelDetail();
    }

  },
  onShow() {
    this.updateParentUserId()
  },
  onReady() {
    // 页面渲染完成后，初始化各种高度计算
    this.$nextTick(() => {
      this.initStickyHeight();
      this.calculateBottomBarHeight();
    });
  },
  methods: {
    closePosterModal() {
      this.showPosterModal = false;
    },
    copyHighlights() {
      // 解析富文本HTML为纯文本
      let plainText = this.parseHtmlToText(this.travel.highlights);

      uni.setClipboardData({
        data: plainText,
        success: () => {
          uni.showToast({
            title: '复制成功',
            icon: 'success'
          });
        }
      });
    },

    // 解析HTML为纯文本，保留换行结构
    parseHtmlToText(html) {
      if (!html) return '';

      let text = html;

      // 替换<br/>和<br>为换行符
      text = text.replace(/<br\s*\/?>/gi, '\n');

      // 替换</p>为换行符（段落结束）
      text = text.replace(/<\/p>/gi, '\n');

      // 替换<p>为换行符（段落开始，但第一个段落不需要换行）
      text = text.replace(/<p[^>]*>/gi, '\n');

      // 移除所有HTML标签
      text = text.replace(/<[^>]*>/g, '');

      // 解码HTML实体
      text = text.replace(/&nbsp;/g, ' ');
      text = text.replace(/&amp;/g, '&');
      text = text.replace(/&lt;/g, '<');
      text = text.replace(/&gt;/g, '>');
      text = text.replace(/&quot;/g, '"');

      // 清理多余的换行符和空格
      text = text.replace(/\n\s*\n/g, '\n'); // 多个连续换行符合并为一个
      text = text.replace(/^\n+/, ''); // 移除开头的换行符
      text = text.replace(/\n+$/, ''); // 移除结尾的换行符
      text = text.replace(/\s+/g, ' '); // 多个连续空格合并为一个

      return text.trim();
    },
    async openShare() {
      this.shareUrl = `pages/travel/detail?id=${this.travelId}&parent_user_id=${this.userInfo.id || ''}`
      if (!this.qrcode) {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });
        this.qrcode = await this.$api.getQrcode(this.shareUrl);
      }
      this.showPosterModal = true;
      uni.hideLoading();
    },
    // 初始化sticky元素高度
    initStickyHeight() {
      const query = uni.createSelectorQuery();
      query.select('.u-sticky').boundingClientRect();
      query.exec((res) => {
        if (res[0]) {
          this.stickyHeight = res[0].height;
          console.log('Sticky height:', this.stickyHeight);
        }
      });
    },
    
    // 计算底部操作栏高度，用于动态调整内容边距
    calculateBottomBarHeight() {
      const query = uni.createSelectorQuery();
      query.select('.bottom-bar').boundingClientRect();
      query.exec((res) => {
        if (res[0]) {
          const bottomBarHeight = res[0].height;
          console.log('Bottom bar height:', bottomBarHeight);
          
          // 动态设置页面底部边距
          this.$nextTick(() => {
            const pageContainer = document.querySelector('.travel-detail');
            if (pageContainer) {
              pageContainer.style.paddingBottom = `${bottomBarHeight + 20}px`;
            }
          });
        }
      });
    },
    
    changeTab(index) {
      console.log('changeTab', index);
      this.current = index;
      
      // 定义锚点映射
      const anchorMap = {
        0: 'highlights',
        1: 'details', 
        2: 'costIncluded',
        3: 'costExcluded',
        4: 'refundRules',
        5: 'bookingNotice'
      };
      
      const targetId = anchorMap[index];
      if (targetId) {
        // 使用uni.createSelectorQuery获取元素相对于页面的绝对位置
        const query = uni.createSelectorQuery();
        query.select(`#${targetId}`).boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec((res) => {
          if (res[0] && res[1]) {
            const targetElement = res[0];
            const scrollOffset = res[1];
            
            // 计算目标元素相对于页面的绝对位置
            const absoluteTop = targetElement.top + scrollOffset.scrollTop;
            
            // 减去sticky高度，确保目标元素顶部与sticky底部对齐
            const targetScrollTop = absoluteTop - 60
            
            console.log('Target element:', targetElement);
            console.log('Scroll offset:', scrollOffset);
            console.log('Absolute top:', absoluteTop);
            console.log('Target scroll top:', targetScrollTop);
            
            // 执行滚动
            uni.pageScrollTo({
              scrollTop: targetScrollTop,
              duration: 300
            });
          }
        });
      }
    },
    onPosterUploaded(url) {
      this.imageUrl = url;
    },
    formatDateKey(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    isDateSelected(date) {
      if (!this.selectedCalendarDate) return false
      return this.formatDateKey(date) === this.formatDateKey(this.selectedCalendarDate.date)
    },
    isToday(date) {
      const today = new Date()
      return this.formatDateKey(date) === this.formatDateKey(today)
    },
    showCalendar() {
      // 如果有选中的日期，跳转到对应月份
      if (this.selectedDateIndex !== -1 && this.dateList.length > 0) {
        const selectedDate = this.dateList[this.selectedDateIndex];
        const dateParts = selectedDate.fullDate.split('-');
        this.currentYear = parseInt(dateParts[0]);
        this.currentMonth = parseInt(dateParts[1]);
        console.log('selectedDate.fullDate',selectedDate.fullDate)
        // 设置日历中选中的日期
        this.selectedCalendarDate = {
          date: new Date(selectedDate.fullDate),
          dateKey: selectedDate.fullDate,
          price: selectedDate.adultPrice,
          stockStatus: selectedDate.stockStatus,
          stockText: selectedDate.stockText
        };
      }
      this.showCalendarPopup = true;
    },
    prevYear() {
      this.currentYear--
    },
    nextYear() {
      this.currentYear++
    },
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12
        this.currentYear--
      } else {
        this.currentMonth--
      }
    },
    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1
        this.currentYear++
      } else {
        this.currentMonth++
      }
    },
    selectCalendarDate(date) {
      if (date.isDisabled) return

      // 更新选中的日历日期
      this.selectedCalendarDate = {
        date: date.date,
        dateKey: date.dateKey,
        price: date.price,
        stockStatus: date.stockStatus,
        stockText: date.stockText
      };
    },
    confirmDateSelection() {
      if (!this.selectedCalendarDate) {
        uni.showToast({
          title: this.textMap.selectDate,
          icon: 'none'
        })
        return
      }

      // 找到对应的日期索引
      const selectedDateKey = this.selectedCalendarDate.dateKey
      const dateIndex = this.dateList.findIndex(date => date.fullDate === selectedDateKey)

      if (dateIndex !== -1) {
        this.selectedDateIndex = dateIndex
        this.showCalendarPopup = false

        // 滚动到选中的日期位置
        this.$nextTick(() => {
          const itemWidth = 120 + 16; // 卡片宽度 + 间距
          this.dateScrollLeft = dateIndex * itemWidth;
        });

        uni.showToast({
          title: this.textMap.dateSelectSuccess,
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: this.textMap.dateNotAvailable,
          icon: 'none'
        })
      }
    },
    getSkuName(sku) {
      if (!sku) return '';
      if (!sku.spec_combination) return '';
      console.log('sku', sku);
      // spec_combination: {"人数":"2-4人","套餐":"奢享双卧四日"}
      const specCombination = JSON.parse(sku.spec_combination);
      // 格式化map中的value，用|分隔展示
      const specNames = Object.values(specCombination).map(value => value.replace(/,/g, '|'));
      return specNames.join(' | ');
    },
    // 加载旅行商品详情
    loadTravelDetail() {
      if (this.loading) return;

      this.loading = true;

      // 获取旅行商品详情
      this.$api.getTravelDetail(this.travelId).then(result => {
        console.log('旅行商品详情:', result);

        if (result) {
          this.travel = result;

          // 重置页面标题
          uni.setNavigationBarTitle({
            title: result.name
          });
          this.travelImages = (result.images || '').split(',')
          // if (result.specs && result.specs.length > 0) {
          //   this.specList = result.specs;
          // }
          // 获取SKU数据
          this.loadTravelSkuList();
        }
      }).finally(() => {
        this.loading = false;
      });
    },

    // 加载旅行SKU列表
    loadTravelSkuList() {
      const params = {
        travel_id: this.travelId,
        status: 1 // 只获取启用的SKU
      };

      this.$api.getTravelSkuList(params).then(result => {
        console.log('旅行SKU列表:', result);

        if (result && result.length > 0) {
          this.skuList = result.map(sku => {
            // 根据dailyStocks中的最低成人价, 判断is_group取拼团价格
            const minAdultPrice = Math.min(...sku.dailyStocks.map(stock => stock.adult_price));
            return {
              ...sku,
              price: minAdultPrice
            }
          })

          // 初始化规格选择
          if (this.skuList.length > 0 && Object.keys(this.selectedSpecs).length === 0) {
            this.initSelectedSpecs();
          }

          // 生成日期数据
          this.generateDateList();
        }
      })
    },

    // 生成日期列表
    generateDateList() {
      if (this.selectedSkuIndex === -1 || !this.skuList[this.selectedSkuIndex]) {
        this.dateList = [];
        return;
      }

      const selectedSku = this.skuList[this.selectedSkuIndex];

      // 获取日期库存数据
      this.loadTravelSkuStockList(selectedSku.id);
    },
    // 处理价格，如果小数位不为0则显示2位小数，如果小数位为0，不显示小数
    handlePrice(price) {
      if (price.toString().split('.')[1] === '00') {
        return price.toString().split('.')[0];
      }
      return price
    },
    // 加载旅行SKU库存列表
    loadTravelSkuStockList(skuId) {
      const params = {
        travel_sku_id: skuId,
        status: 1 // 只获取可预订的库存
      };

      this.$api.getTravelSkuStockList(params).then(result => {
        console.log('旅行SKU库存列表:', result);

        if (result && result.length > 0) {
          // 处理库存数据
          this.dateList = result.map(stock => {
            const date = new Date(stock.travel_date);
            const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

            // 计算总可购人数
            const totalAvailable = stock.adult_total_stock + stock.child_total_stock;

            // 判断库存状态
            let stockStatus = 'normal'; // normal, low, sold
            let stockText = '';

            if (totalAvailable <= 0) {
              stockStatus = 'sold';
              stockText = '已售罄';
            } else if (totalAvailable <= 5) {
              stockStatus = 'low';
              stockText = `仅剩${totalAvailable}人`;
            } else {
              stockStatus = 'normal';
              // stockText = `可购${totalAvailable}人`;
            }

            return {
              id: stock.id,
              week: weekNames[date.getDay()],
              month: date.getMonth() + 1,
              day: date.getDate(),
              fullDate: stock.travel_date,
              adultPrice: this.handlePrice(stock.adult_price),
              childPrice: this.handlePrice(stock.child_price),
              adultOriginalPrice: this.handlePrice(stock.adult_original_price),
              childOriginalPrice: this.handlePrice(stock.child_original_price),
              adultAvailable: stock.adult_total_stock,
              childAvailable: stock.child_total_stock,
              totalAvailable: totalAvailable,
              stockStatus: stockStatus,
              stockText: stockText,
              status: stock.status,
              is_group: stock.is_group, // 新增is_group字段
              group_adult_people: stock.group_adult_people,
            };
          });

          // 构建日期映射
          this.buildDateMap();
        }
      }).catch(error => {
        console.error('旅行SKU库存列表:', error);
      });
    },

    // 构建日期映射
    buildDateMap() {
      this.dateMap.clear();
      this.dateList.forEach(date => {
        this.dateMap.set(date.fullDate, {
          adultPrice: date.adultPrice,
          childPrice: date.childPrice,
          stockStatus: date.stockStatus,
          stockText: date.stockText,
          status: date.status,
          is_group: date.is_group // 新增is_group字段
        });
      });
    },

    // 生成默认日期列表
    generateDefaultDateList() {
      const dates = [];
      const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const today = new Date();

      for (let i = 0; i < 5; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);

        dates.push({
          id: i,
          week: weekNames[date.getDay()],
          month: date.getMonth() + 1,
          day: date.getDate(),
          fullDate: this.formatDate(date),
          adultPrice: this.skuList[this.selectedSkuIndex] ? this.skuList[this.selectedSkuIndex].price : 0,
          childPrice: this.skuList[this.selectedSkuIndex] ? this.skuList[this.selectedSkuIndex].price * 0.8 : 0,
          adultOriginalPrice: this.skuList[this.selectedSkuIndex] ? this.skuList[this.selectedSkuIndex].price : 0,
          childOriginalPrice: this.skuList[this.selectedSkuIndex] ? this.skuList[this.selectedSkuIndex].price * 0.8 : 0,
          adultAvailable: 10,
          childAvailable: 5,
          totalAvailable: 15,
          stockStatus: 'normal',
          stockText: '可购15人',
          status: 1,
          is_group: 0 // 默认不是拼团产品
        });
      }

      this.dateList = dates;
      this.buildDateMap();
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 选择SKU
    selectSku(index) {
      this.selectedSkuIndex = index;
      this.selectedDateIndex = 0; // 重置日期选择
      this.generateDateList(); // 重新生成日期列表

      // 计算滚动位置，将选中的SKU滚动到第一个位置
      this.$nextTick(() => {
        const itemWidth = 120 + 24; // 卡片宽度 + 间距
        this.skuScrollLeft = index * itemWidth;
      });
    },

    // 选择规格
    selectSpec(specKey, option) {
      this.$set(this.selectedSpecs, specKey, option);
      this.updateSelectedSku();
    },

    // 根据规格选择更新SKU
    updateSelectedSku() {
      const matchedSku = this.skuList.find(sku => {
        if (!sku.spec_combination) return false;
        try {
          const specs = JSON.parse(sku.spec_combination);
          return Object.keys(this.selectedSpecs).every(key =>
            specs[key] === this.selectedSpecs[key]
          );
        } catch (e) {
          return false;
        }
      });

      if (matchedSku) {
        this.selectedSkuIndex = this.skuList.indexOf(matchedSku);
        this.generateDateList(); // 重新生成日期列表
      } else {
        // 如果未找到匹配的SKU，重置选择
        this.selectedDateIndex = -1;
        this.dateList = [];
      }
    },

    // 初始化规格选择
    initSelectedSpecs() {
      if (this.skuList.length > 0) {
        const firstSku = this.skuList[0];
        if (firstSku.spec_combination) {
          try {
            const specs = JSON.parse(firstSku.spec_combination);
            this.selectedSpecs = { ...specs };
          } catch (e) {
            console.error('解析SKU规格失败:', e);
          }
        }
      }
    },

    // 选择日期
    selectDate(index) {
      const selectedDate = this.dateList[index];

      // 检查库存状态
      if (selectedDate.stockStatus === 'sold' || selectedDate.status === 0) {
        uni.showToast({
          title: this.textMap.dateNotAvailable,
          icon: 'none'
        });
        return;
      }

      this.selectedDateIndex = index;

      // 计算滚动位置，将选中的日期滚动到第一个位置
      this.$nextTick(() => {
        const itemWidth = (uni.getSystemInfoSync().windowWidth - 64 - 64) / 5; // 屏幕宽度减去左右边距，除以5个卡片
        this.dateScrollLeft = index * itemWidth;
      });
    },

    // 下一步
    goToNext() {
      if (this.selectedSkuIndex === -1) {
        uni.showToast({
          title: this.textMap.selectPackage,
          icon: 'none'
        });
        return;
      }

      if (this.selectedDateIndex === -1 || this.dateList.length === 0) {
        uni.showToast({
          title: this.textMap.selectDateRequired,
          icon: 'none'
        });
        return;
      }

      const selectedSku = this.skuList[this.selectedSkuIndex];
      const selectedDate = this.dateList[this.selectedDateIndex];

      // 检查库存状态
      if (selectedDate.stockStatus === 'sold' || selectedDate.status === 0) {
        uni.showToast({
          title: this.textMap.dateNotAvailable,
          icon: 'none'
        });
        return;
      }

      console.log('选择的套餐:', selectedSku);
      console.log('选择的日期:', selectedDate);

      // 跳转到下一步页面
      this.$goPage({
        needLogin: true,
        url: `/pages/travel/confirm?travelId=${this.travelId}&skuId=${selectedSku.id}&skuDateId=${selectedDate.id}`
      });
    },

    // 邀请好友
    inviteFriend() {
      if (this.selectedSkuIndex === -1) {
        uni.showToast({
          title: this.textMap.selectPackage,
          icon: 'none'
        });
        return;
      }

      if (this.selectedDateIndex === -1 || this.dateList.length === 0) {
        uni.showToast({
          title: this.textMap.selectDateRequired,
          icon: 'none'
        });
        return;
      }

      const selectedSku = this.skuList[this.selectedSkuIndex];
      const selectedDate = this.dateList[this.selectedDateIndex];

      // 检查库存状态
      if (selectedDate.stockStatus === 'sold' || selectedDate.status === 0) {
        uni.showToast({
          title: this.textMap.dateNotAvailable,
          icon: 'none'
        });
        return;
      }

      console.log('邀请好友，选择的套餐:', selectedSku);
      console.log('邀请好友，选择的日期:', selectedDate);

      // 跳转到分销确认页面
      this.$goPage({
        needLogin: true,
        url: `/pages/travel/confirmShare?travelId=${this.travelId}&skuId=${selectedSku.id}&skuDateId=${selectedDate.id}`
      });
    }
  },
  // 分享给朋友
  onShareAppMessage() {
    if (this.userInfo.user_type === 3) {
      return {
        title: this.travel.name,
        path: `/pages/travel/detail?id=${this.travelId}&parent_user_id=${this.userInfo.id || ''}`,
      }
    } else {
      return {
        title: this.travel.name,
        path: `/pages/travel/detail?id=${this.travelId}`,
      }
    }
  },
}
</script>

<style lang="scss">
.travel-detail {
  background-color: #f5f5f5;
  padding-bottom: 140rpx; // 为底部操作栏预留足够空间，确保内容不被遮挡

  // 价格日历弹窗样式
  .calendar-popup {
    background: #fff;
    display: flex;
    flex-direction: column;

    .calendar-header {
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .calendar-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        text-align: center;
        display: block;
        margin-bottom: 24rpx;
      }

      .calendar-nav {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 32rpx;

        .nav-btn {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f5f5f5;
          border-radius: 30rpx;
          font-size: 24rpx;
          color: #666;
          cursor: pointer;

          &:active {
            background: #e0e0e0;
          }
        }

        .current-month {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          min-width: 200rpx;
          text-align: center;
        }
      }
    }

    .week-header {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      padding: 24rpx 32rpx 16rpx;

      .week-item {
        text-align: center;
        font-size: 28rpx;
        color: #666;
        padding: 16rpx 0;

        &.weekend {
          color: #FF8D1A;
        }
      }
    }

    .date-grid {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 8rpx;
      padding: 0 32rpx;
      flex: 1;

      .date-item {
        position: relative;
        height: 120rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 12rpx;
        cursor: pointer;
        border: 2rpx solid transparent;

        &.available {
          .date-number {
            color: #333 !important;
          }
        }

        .date-number {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 4rpx;
        }

        .date-price {
          margin-bottom: 4rpx;

          .price-text {
            font-size: 24rpx;
            color: #FF6600;
            // font-weight: bold;
          }
        }

        .date-status {
          .status-text {
            font-size: 16rpx;
            display: block;

            &.normal {
              color: #52c41a;
            }

            &.low {
              color: #faad14;
            }

            &.sold {
              color: #ff4d4f;
            }
          }
        }

        &.prev-month,
        &.next-month {
          .date-number {
            color: #ccc;
          }
        }

        &.current-month {
          .date-number {
            color: #333;
          }
        }

        &.today {
          background: #fff3e6;
          border-color: #FF8D1A;

          .date-number {
            color: #FF8D1A;
            font-weight: 600;
          }
        }

        &.selected {
          background: #FF8D1A;
          border-color: #FF8D1A;

          .date-number,
          .price-text,
          .status-text {
            color: #fff !important;
          }
        }

        &.disabled {
          opacity: 0.3;
          pointer-events: none;

          .date-number {
            color: #ccc !important;
          }
        }
      }
    }

    .calendar-footer {
      padding: 32rpx;
      padding-bottom: 60rpx;
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .selected-info {
        flex: 1;

        .selected-date {
          font-size: 28rpx;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }

        .selected-price {
          font-size: 24rpx;
          color: #FF6600;
          font-weight: bold;
        }
      }

      .confirm-btn {
        width: 300rpx;
      }
    }
  }

  // 日期选择区域添加日历按钮
  .date-section {
    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .calendar-btn {
        font-size: 24rpx;
        color: #FF8D1A;
        padding: 8rpx 16rpx;
        border: 1rpx solid #FF8D1A;
        border-radius: 20rpx;
        cursor: pointer;

        &:active {
          background: #fff3e6;
        }
      }
    }
  }

  // 拼团信息展示
  .group-info-section {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .title-text {
        font-size: 28rpx;
        color: #333333;
        font-weight: bold;
      }

      .group-status {
        font-size: 24rpx;
        color: #FF8D1A;
        font-weight: bold;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        border: 1rpx solid #FF8D1A;

        &.success {
          color: #52c41a;
          border-color: #52c41a;
        }

        &.pending {
          color: #faad14;
          border-color: #faad14;
        }

        &.upcoming {
          color: #FF8D1A;
          border-color: #FF8D1A;
        }
      }
    }

    .group-progress {
      margin-bottom: 24rpx;

      .progress-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .progress-info {
          font-size: 24rpx;
          color: #333333;
          display: flex;
          align-items: baseline;

          .current-count,
          .target-count {
            font-size: 32rpx;
            color: #FF6600;
            font-weight: bold;
          }

          .separator {
            margin: 0 4rpx;
          }

          .unit {
            font-size: 20rpx;
            color: #333333;
          }
        }

        .progress-percentage {
          font-size: 24rpx;
          color: #FF6600;
          font-weight: bold;
        }
      }

      .progress-bar {
        height: 12rpx;
        background-color: #f0f0f0;
        border-radius: 6rpx;
        overflow: hidden;
        margin-bottom: 16rpx;
      }

      .progress-fill {
        height: 100%;
        background-color: #FF8D1A;
        border-radius: 6rpx;
      }

      .group-details {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        font-size: 24rpx;
        color: #666666;

        .detail-item {
          display: flex;
          align-items: center;

          .detail-label {
            margin-right: 8rpx;
          }

          .detail-value {
            font-weight: bold;
            color: #FF6600;

            &.success {
              color: #52c41a;
            }
          }
        }
      }
    }

    .group-notice {
      display: flex;
      align-items: center;
      background: #fffbe6;
      border: 1rpx solid #ffe58f;
      border-radius: 12rpx;
      padding: 16rpx 24rpx;
      margin-top: 24rpx;

      .notice-icon {
        font-size: 32rpx;
        color: #faad14;
        margin-right: 12rpx;
      }

      .notice-text {
        font-size: 24rpx;
        color: #faad14;
        line-height: 1.5;
      }
    }
  }

  // 轮播图
  .travel-swiper {
    width: 100%;
    height: 360rpx;
    background: #f8f8f8;

    .swiper {
      width: 100%;
      height: 100%;

      .swiper-image {
        width: 100%;
        height: 100%;
      }
    }
  }

  // 产品基本信息
  .travel-info {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .travel-name {
      font-size: 28rpx;
      color: #333333;
      font-weight: bold;
      line-height: 1.4;
      margin-bottom: 16rpx;
    }

    .travel-description {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.5;
      margin-bottom: 16rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .travel-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .sales-info {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  // SKU选择
  .sku-section {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    // 规格选择
    .spec-selector {
      // margin-top: 24rpx;
      // padding-top: 24rpx;
      // border-top: 1rpx solid #f0f0f0;

      .spec-section {
        margin-bottom: 24rpx;

        .spec-name {
          font-size: 28rpx;
          color: #333333;
          font-weight: bold;
          margin-bottom: 16rpx;
          display: block;
        }
      }
    }

    .section-title {
      margin-bottom: 24rpx;

      .title-text {
        font-size: 28rpx;
        color: #333333;
        font-weight: bold;
      }
    }

    .sku-scroll {
      white-space: nowrap;
    }

    .sku-list {
      display: flex;
      gap: 24rpx;

      .sku-item {
        flex-shrink: 0;
        width: 240rpx;
        padding: 12rpx 24rpx;
        background: #FFFFFF;
        border-radius: 12rpx;
        border: 2rpx solid #e0e0e0;
        position: relative;

        &.active {
          border: 2rpx solid #FFC300;
          background: #f8f8f8;
        }

        .sku-header {
          width: 100%;
          font-size: 24rpx;
          color: #333333;
          line-height: 1.4;
          padding-right: 12rpx;
          // 换行
          white-space: pre-wrap;
          word-wrap: break-word;
          word-break: break-all;
          overflow-wrap: break-word;
          text-align: left;
          text-align-last: left;
          text-align-all: left;

        }

        .sku-price-section {
          display: flex;
          align-items: baseline;

          .sku-price {
            font-size: 28rpx;
            color: #FF6600;
            font-weight: bold;
            margin-right: 4rpx;
          }

          .sku-unit {
            font-size: 20rpx;
            color: #333333;
          }
        }

        .sku-desc {
          font-size: 20rpx;
          color: #999999;
        }

        .check-icon {
          position: absolute;
          top: -2rpx;
          right: -2rpx;
          width: 40rpx;
          height: 40rpx;
          background: #FFC300;
          border-radius: 0 16rpx 0 16rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 2rpx solid #FFC300;

          .check-text {
            font-size: 20rpx;
            color: #FFFFFF;
            font-weight: bold;
          }
        }
      }
    }
  }

  // 日期选择
  .date-section {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;

    .section-title {
      margin-bottom: 24rpx;

      .title-text {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }
    }

    .date-scroll {
      white-space: nowrap;
    }

    .date-list {
      display: flex;
      gap: 16rpx;

      .date-item {
        flex-shrink: 0;
        width: 120rpx;
        padding: 8rpx 12rpx;
        background: #FFFFFF;
        border-radius: 12rpx;
        border: 2rpx solid #e0e0e0;
        text-align: center;
        position: relative;

        &.active {
          border: 2rpx solid #FFC300;
          background: #f8f8f8;
        }

        &.disabled {
          background: #f5f5f5;
          border-color: #d0d0d0;
          opacity: 0.6;
          cursor: not-allowed;
        }

        .date-week {
          font-size: 20rpx;
          color: #666666;
          display: block;
          margin-bottom: 4rpx;
        }

        .date-day {
          font-size: 24rpx;
          color: #333333;
          font-weight: bold;
          display: block;
          margin-bottom: 4rpx;
        }

        .date-price-section {
          display: flex;
          align-items: baseline;
          justify-content: center;
          margin-bottom: 4rpx;

          .date-price {
            font-size: 24rpx;
            color: #FF6600;
            font-weight: bold;
          }

          .date-unit {
            font-size: 18rpx;
            color: #333333;
            margin-left: 2rpx;
          }
        }

        .date-stock {
          font-size: 18rpx;
          display: block;

          &.normal {
            color: #52c41a;
          }

          &.low {
            color: #faad14;
          }

          &.sold {
            color: #ff4d4f;
          }
        }

        .check-icon {
          position: absolute;
          top: -2rpx;
          right: -2rpx;
          width: 32rpx;
          height: 32rpx;
          background: #FFC300;
          border-radius: 0 16rpx 0 16rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 2rpx solid #FFC300;

          .check-text {
            font-size: 16rpx;
            color: #FFFFFF;
            font-weight: bold;
          }
        }
      }
    }
  }

  // 底部操作栏
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #FFFFFF;
    padding: 24rpx 32rpx;
    padding-bottom: calc(0rpx + env(safe-area-inset-bottom)); // 适配安全区域
    border-top: 1rpx solid #f0f0f0;
    z-index: 100;
    display: flex;
    align-items: center;
    gap: 24rpx;
    min-height: 120rpx; // 设置最小高度，确保内容不被遮挡

    .customer-service {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;
      min-height: 80rpx; // 设置最小高度

      .service-btn {
        background: transparent;
        border: none;
        padding: 0;
        margin: 0;
        line-height: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 3;
        opacity: 0;

        &::after {
          border: none;
        }
      }

      .service-icon {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .service-text {
        font-size: 28rpx;
        color: #333;
      }
    }

    .distributor-actions {
      flex: 1;
      display: flex;
      gap: 24rpx;

      .invite-btn {
        flex-grow: 1;
      }
    }

    .action-section {
      flex-grow: 1;
      display: flex;
      align-items: center;
      justify-content: center;

      .next-btn {
        width: 100%;
        height: 88rpx;
        background: #FFC300;
        color: #FFFFFF;
        border: none;
        border-radius: 44rpx;
        font-size: 28rpx;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;

        &:active {
          background: #4a8ce0;
        }
      }
    }
  }

  // 产品详情
  .detail-section {
    background: #FFFFFF;
    padding: 24rpx;
    margin-bottom:20rpx;
    scroll-margin-top: 120rpx; // 为锚点定位添加顶部边距

    .section-title {
      margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title-text {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }

      .calendar-btn {
        font-size: 24rpx;
        color: #FF8D1A;
        padding: 8rpx 16rpx;
        border: 1rpx solid #FF8D1A;
        border-radius: 20rpx;
        cursor: pointer;

        &:active {
          background: #fff3e6;
        }
      }
    }

    .detail-content {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.6;
    }
  }

  // 加载状态
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background: #f5f5f5;

    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #FFC300;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 24rpx;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666666;
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
}
</style>
